from sqlalchemy.orm import Session
from fastapi import HTTPException, status
from .. import models, schemas
from datetime import datetime
from typing import Optional

def create_post(db: Session, post: schemas.PostCreate, author_id: str):
    """创建帖子"""
    db_post = models.Post(
        title=post.title,
        content=post.content,
        author_id=author_id
    )
    db.add(db_post)
    db.commit()
    db.refresh(db_post)
    return db_post

def get_post_list(db: Session, skip: int = 0, limit: int = 10):
    """获取帖子列表"""
    return db.query(models.Post).order_by(
        models.Post.created_at.desc()
    ).offset(skip).limit(limit).all()

def get_post(db: Session, post_id: str):
    """获取帖子详情"""
    post = db.query(models.Post).filter(models.Post.id == post_id).first()
    if not post:
        raise HTTPException(status_code=404, detail="帖子不存在")
    return post

def update_post(db: Session, post_id: str, post_update: schemas.PostUpdate, current_user_id: str):
    """更新帖子"""
    db_post = get_post(db, post_id)
    if db_post.author_id != current_user_id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只能修改自己的帖子"
        )
    
    if post_update.title is not None:
        db_post.title = post_update.title
    if post_update.content is not None:
        db_post.content = post_update.content
    
    db.commit()
    db.refresh(db_post)
    return db_post

def delete_post(db: Session, post_id: str, current_user_id: str):
    """删除帖子"""
    db_post = get_post(db, post_id)
    if db_post.author_id != current_user_id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只能删除自己的帖子"
        )
    
    db.delete(db_post)
    db.commit()
    return {"message": "帖子已删除"}

def create_comment(
    db: Session, 
    post_id: str,
    comment: schemas.CommentCreate, 
    author_id: str,
    parent_id: Optional[str] = None
):
    """创建评论"""
    # 检查帖子是否存在
    post = get_post(db, post_id)
    
    # 如果有父评论ID，检查父评论是否存在且属于同一个帖子
    if parent_id:
        parent_comment = db.query(models.Comment).filter(
            models.Comment.id == parent_id,
            models.Comment.post_id == post_id
        ).first()
        if not parent_comment:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="父评论不存在或不属于该帖子"
            )
    
    db_comment = models.Comment(
        content=comment.content,
        post_id=post_id,
        author_id=author_id,
        parent_id=parent_id
    )
    db.add(db_comment)
    db.commit()
    db.refresh(db_comment)
    return db_comment

def get_post_comment_list(db: Session, post_id: str, skip: int = 0, limit: int = 10):
    """获取帖子的评论列表（只获取顶层评论）"""
    return db.query(models.Comment).filter(
        models.Comment.post_id == post_id,
        models.Comment.parent_id == None  # 只获取顶层评论
    ).order_by(
        models.Comment.created_at.desc()
    ).offset(skip).limit(limit).all()

def get_comment_replies(db: Session, comment_id: str, skip: int = 0, limit: int = 10):
    """获取评论的回复列表"""
    return db.query(models.Comment).filter(
        models.Comment.parent_id == comment_id
    ).order_by(
        models.Comment.created_at.asc()
    ).offset(skip).limit(limit).all()

def get_user_posts(db: Session, user_id: str, skip: int = 0, limit: int = 10):
    """获取指定用户的所有帖子"""
    return db.query(models.Post).filter(
        models.Post.author_id == user_id
    ).order_by(
        models.Post.created_at.desc()
    ).offset(skip).limit(limit).all()

def like_post(db: Session, post_id: str, user_id: str):
    """给帖子点赞"""
    # 检查帖子是否存在
    post = get_post(db, post_id)
    if not post:
        raise HTTPException(status_code=404, detail="帖子不存在")
    
    # 检查是否已经点赞
    existing_like = db.query(models.PostLike).filter(
        models.PostLike.post_id == post_id,
        models.PostLike.user_id == user_id
    ).first()
    
    if existing_like:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="已经点赞过这个帖子"
        )
    
    # 创建点赞记录
    like = models.PostLike(
        post_id=post_id,
        user_id=user_id
    )
    db.add(like)
    
    # 更新帖子点赞数
    post.post_likes_count += 1
    
    db.commit()
    return post

def unlike_post(db: Session, post_id: str, user_id: str):
    """取消帖子点赞"""
    # 检查帖子是否存在
    post = get_post(db, post_id)
    if not post:
        raise HTTPException(status_code=404, detail="帖子不存在")
    
    # 查找点赞记录
    like = db.query(models.PostLike).filter(
        models.PostLike.post_id == post_id,
        models.PostLike.user_id == user_id
    ).first()
    
    if not like:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="还没有点赞过这个帖子"
        )
    
    # 删除点赞记录
    db.delete(like)
    
    # 更新帖子点赞数
    post.post_likes_count -= 1
    
    db.commit()
    return post

def check_post_liked(db: Session, post_id: str, user_id: str) -> bool:
    """检查用户是否已经点赞过帖子"""
    like = db.query(models.PostLike).filter(
        models.PostLike.post_id == post_id,
        models.PostLike.user_id == user_id
    ).first()
    return like is not None 